package com.richapp.launcher.database.system.dao;

import java.sql.SQLException;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.List;

import com.j256.ormlite.dao.GenericRawResults;
import com.j256.ormlite.field.DataType;
import com.richapp.launcher.database.system.SystemBaseDao;
import com.richapp.launcher.database.system.mode.DeviceModel;
import com.richapp.launcher.database.system.mode.DeviceModelHistory;
import com.richapp.launcher.serialport.gateway.GatewaytConstant;

import android.content.Context;
import android.util.Log;

public class DeviceModelHistoryDao extends SystemBaseDao<DeviceModelHistory>{

	private DecimalFormat format = new DecimalFormat("0.00000000");
	private static final String daySum = "select id ,boxCpuId,deviceId,deviceNumber,way,deviceName,deviceStatus,lastOpenTime,lastCloseTime,sum(powerConsumption) as powerConsumption from deviceHistory where lastOpenTime > ? group by boxCpuId,deviceId,deviceNumber order by boxCpuId,deviceId,deviceNumber ";

	public DeviceModelHistoryDao(Context context) {
		super(context,DeviceModelHistory.class);
	}
	
	
	public void addModelHisotry(DeviceModel dm){
		if(GatewaytConstant.getDeviceMonitorMap().containsKey(dm.getDeviceId())){
			if(Boolean.parseBoolean(dm.getMonitorState())){
				try {
					DeviceModelHistory dmh = getLastHistory(dm.getBoxCpuId(),dm.getDeviceId(),dm.getDeviceNumber(),dm.getWay());;
					if("FF".equals(dm.getDeviceStatus())){	//设备开
						if(dmh == null || dmh.getLastOpenTime() > 0){
							dmh = new DeviceModelHistory();
							
							dmh.setBoxCpuId(dm.getBoxCpuId());
							dmh.setDeviceId(dm.getDeviceId());
							dmh.setDeviceNumber(dm.getDeviceNumber());
							dmh.setWay(dm.getWay());
							dmh.setDeviceName(dm.getDeviceName());
							
							dmh.setDeviceStatus(dm.getDeviceStatus());
							dmh.setLastOpenTime(System.currentTimeMillis());
							gettOp().create(dmh);
						}else{
							dmh.setDeviceStatus(dm.getDeviceStatus());
							dmh.setLastOpenTime(System.currentTimeMillis());
							gettOp().update(dmh);
						}
					}else if("00".equals(dm.getDeviceStatus())){	//设备关
						if(dmh != null){
							if(dmh.getLastCloseTime() <= 0){
								dmh.setLastCloseTime(System.currentTimeMillis());
								double powerConsumption = (Double.parseDouble(dm.getPower()) * (dmh.getLastCloseTime() - dmh.getLastOpenTime())) /(double)(1000*60*60)/(double)1000;
								powerConsumption =  powerConsumption * 1.05;
								Log.i(getClass().getName(),"耗电量:" + format.format(powerConsumption));
								dmh.setPowerConsumption(format.format(powerConsumption));
								gettOp().update(dmh);
							}
						}
					}else{
						//其他状态忽略不计
					}
				} catch (Exception e) {
					Log.e(getClass().getName(), e.getMessage());
				}
			}
		}
		
	}
	
	public DeviceModelHistory getLastHistory(String boxCpuId,String deviceId,String deviceNumber,String way){
		DeviceModelHistory dmh = null;
		try {
			dmh = gettOp().queryBuilder().orderBy("lastOpenTime", false).where().eq("boxCpuId", boxCpuId).and().eq("deviceId", deviceId).and().eq("deviceNumber", deviceNumber).and().eq("way",way).queryForFirst();
		} catch (SQLException e) {
			Log.e(getClass().getName(), e.getMessage());
		}
		return dmh;
	}
	
	public List<DeviceModelHistory> getLastDayPowerConsumptionFromRecord(){
		List<DeviceModelHistory> list = new ArrayList<DeviceModelHistory>();
		try {
			String sumSql = daySum.replace("?", (System.currentTimeMillis()-(24*60*60*1000))+"");
			GenericRawResults<Object[]> rawResults = gettOp().queryRaw(sumSql, new DataType[]{
					DataType.INTEGER,    //0
					DataType.STRING,    //1
					DataType.STRING,    //2
					DataType.STRING,    //3
					DataType.STRING,    //4
					DataType.STRING,    //5
					DataType.STRING,    //6
					DataType.BIG_INTEGER,    //7
					DataType.BIG_INTEGER,    //8
					DataType.STRING,    //9

			});
			DeviceModelHistory dmh = null;
			for(Object[] objs : rawResults){
				dmh = new DeviceModelHistory();
				dmh.setBoxCpuId(objs[1].toString());
				dmh.setDeviceId(objs[2].toString());
				dmh.setDeviceNumber(objs[3].toString());
				dmh.setWay(objs[4].toString());
				dmh.setDeviceName(objs[5].toString());
				dmh.setPowerConsumption(objs[9].toString());
				list.add(dmh);
			}
			rawResults.close();
		} catch (Exception e) {
			Log.e(getClass().getName(), e.getMessage());
		}
		return list;
	}
	
	public List<DeviceModelHistory> getLastWeekPowerConsumptionFromRecord(){
		List<DeviceModelHistory> list = new ArrayList<DeviceModelHistory>();
		try {
			String sumSql = daySum.replace("?", (System.currentTimeMillis()-(7*24*60*60*1000))+"");
			GenericRawResults<Object[]> rawResults = gettOp().queryRaw(sumSql, new DataType[]{
					DataType.INTEGER,    //0
					DataType.STRING,    //1
					DataType.STRING,    //2
					DataType.STRING,    //3
					DataType.STRING,    //4
					DataType.STRING,    //5
					DataType.STRING,    //6
					DataType.BIG_INTEGER,    //7
					DataType.BIG_INTEGER,    //8
					DataType.STRING    //9
			});
			DeviceModelHistory dmh = null;
			for(Object[] objs : rawResults){
				dmh = new DeviceModelHistory();
				dmh.setBoxCpuId(objs[1].toString());
				dmh.setDeviceId(objs[2].toString());
				dmh.setDeviceNumber(objs[3].toString());
				dmh.setWay(objs[4].toString());
				dmh.setDeviceName(objs[5].toString());
				dmh.setPowerConsumption(objs[9].toString());
				list.add(dmh);
			}
			rawResults.close();
		} catch (Exception e) {
			Log.e(getClass().getName(), e.getMessage());
		}
		return list;
	}
	
	public List<DeviceModelHistory> getLastMonthPowerConsumptionFromRecord(){
		List<DeviceModelHistory> list = new ArrayList<DeviceModelHistory>();
		try {
			long time = System.currentTimeMillis()-((long)30*24*60*60*1000);
			String sumSql = daySum.replace("?", time+"");
			GenericRawResults<Object[]> rawResults = gettOp().queryRaw(sumSql, new DataType[]{
					DataType.INTEGER,    //0
					DataType.STRING,    //1
					DataType.STRING,    //2
					DataType.STRING,    //3
					DataType.STRING,    //4
					DataType.STRING,    //5
					DataType.STRING,    //6
					DataType.BIG_INTEGER,    //7
					DataType.BIG_INTEGER,    //8
					DataType.STRING    //9
			});
			DeviceModelHistory dmh = null;
			for(Object[] objs : rawResults){
				dmh = new DeviceModelHistory();
				dmh.setBoxCpuId(objs[1].toString());
				dmh.setDeviceId(objs[2].toString());
				dmh.setDeviceNumber(objs[3].toString());
				dmh.setWay(objs[4].toString());
				dmh.setDeviceName(objs[5].toString());
				dmh.setPowerConsumption(objs[9].toString());
				list.add(dmh);
			}
			rawResults.close();
		} catch (Exception e) {
			Log.e(getClass().getName(), e.getMessage());
		}
		return list;
	}
}
